﻿using System;
using System.Collections.Generic;
using System.Text;
using WorkFlowCore.IRepositories;

namespace WorkFlowCore.Framework.Repositories
{
    public class UnitOfWork : IUnitOfWork
    {
        private List<object> removeList;
        private List<object> addList;
        private bool isActive = false;
        private int beginLevel = 0;

        public UnitOfWork()
        {
            removeList = new List<object>();
            addList = new List<object>();
        }


        public bool Commit()
        {
            beginLevel--;
            //如果开启了多层事务，则最外层才提交 
            if (beginLevel > 0)
            {
                
                return true;
            }
            try
            {
                foreach (var item in removeList)
                {
                    VirtualDB.Remove(item.GetType(), item);
                }
                foreach (var item in addList)
                {
                    VirtualDB.Add(item.GetType(), item);
                }
                VirtualDB.SaveData();
                return true;
            }
            catch (Exception)
            {
                //回滚
                foreach (var item in removeList)
                {
                    if(!VirtualDB.IsContains(item.GetType(), item))
                        VirtualDB.Add(item.GetType(), item);
                }
                foreach (var item in addList)
                {
                    if (VirtualDB.IsContains(item.GetType(), item))
                        VirtualDB.Remove(item.GetType(), item);
                }
                return false;
            }
        }

        public void Dispose()
        {
            removeList.Clear();
            addList.Clear();
            isActive = false;
        }

        public bool IsActive()
        {
            return isActive;
        }

        internal  int Add(params object[] items)
        {
            if (items != null)
            {
                var count = 0;
                foreach (var item in items)
                {
                    count++;
                    addList.Add(item);
                }
                return count;
            }
            return 0;
        }
        internal  int Remove( params object[] items)
        {
            if (items != null)
            {
                var count = 0;
                foreach (var item in items)
                {
                    count++;
                    removeList.Add(item);
                }
                return count;
            }
            return 0;
        }

        internal void Begin()
        {
            beginLevel++;
            if (this.isActive) return;
            isActive = true;
        }
    }
}
